package whu.cn.whushare.ui.main.my;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.androidplus.ui.ToastManager;
import com.androidplus.util.StringUtil;
import com.androidplus.util.ViewMapping;
import com.androidplus.util.ViewMappingUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import whu.cn.whushare.R;
import whu.cn.whushare.bean.User;
import whu.cn.whushare.common.Application;
import whu.cn.whushare.common.UserManager;
import whu.cn.whushare.net.DownloadParams;
import whu.cn.whushare.net.Downloader;
import whu.cn.whushare.ui.common.BaseActivity;
import whu.cn.whushare.ui.main.MainTabActivity;
import whu.cn.whushare.util.EncrypAES;

/**
 * 文件名：LoginActivity
 * 描 述：
 * 作 者：胡平平
 */
@ViewMapping(id = R.layout.activity_login)  //获取登录页面布局文件
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private boolean exit;                   // 退出软件
	@ViewMapping(id = R.id.user_name)       //获取用户名控件
	private EditText mUser;
	@ViewMapping(id = R.id.pass)            //获取用户密码控件
	private EditText mPass;
	@ViewMapping(id = R.id.login)           //获取登录控件
	private Button mLogin;
	@ViewMapping(id = R.id.register)        //获取注册控件
	private TextView mRegister;
    @ViewMapping(id=R.id.forget_password)     //获取忘记密码控件
    private TextView mForgetPassword;
    private User user;
	private UserManager mUserManager;
	private UserManager.UserStatus mLoginType;

    /*
    * 方法名：getStartIntent(Context context)
    * 功 能：获取跳转到当前activity的intent消息
    * 参 数：@param Context context-上下文信息
    * 返回值：@return 跳转到当前activity的intent
    */
	public static Intent getStartIntent(Context context) {
    	return new Intent(context, LoginActivity.class);
	}

	@Override
    /**
     * 初始化当前activity
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		initViews();
		initActions();
	}

    //初始化views
	private void initViews() {
		View root = ViewMappingUtil.mapView(this, this);    //将当前activity与相应的布局文件一一映射
		getTopBar(root);
		mTopBar.title.setText(R.string.login);
	}


    //初始化控件动作，为控件添加事件监听器以响应用户点击操作
    private void initActions() {
		mUserManager = UserManager.getInstance(this);
		mLogin.setOnClickListener(this);
		mPass.setOnClickListener(this);
		mRegister.setOnClickListener(this);
        mForgetPassword.setOnClickListener(this);
	}

	private boolean validateLogin(String user, String pass) {
        //mLoginType=mUserManager.validateUserName(user);
		mLoginType = mUserManager.validateMail(user);
		String msg = mLoginType.getMsg();
		if (!StringUtil.isNullOrEmpty(msg)) {
			toast(msg);
			return false;
		}
		msg = mUserManager.validatePass(pass).getMsg();
		if (!StringUtil.isNullOrEmpty(msg)) {
			toast(msg);
			return false;
		}
		return true;
	}

	@Override
    /**
     * 方法名：onClick(View v)
     * 功 能：根据事件源的不同，响应不同事件源的点击操作
     *       事件源为登录控件时，进行登录操作；
     *       事件源为注册时，跳转到注册页面；
     *       事件源为忘记密码时，跳转到忘记密码页面；
     * 参 数：@param v - 发生点击事件的控件
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login:
			String userName = mUser.getText().toString();
			String pass = mPass.getText().toString();
			if (validateLogin(userName, pass)) {
				Downloader.getInstance(this).login(userName, pass, 1, this, pass);
			}
			break;
		case R.id.register:
			startActivity(RegisterActivity.getStartIntent(this));
			break;
        case R.id.forget_password:
            startActivity(ForgetPassActivity.getStartIntent(this));
            break;
		default:
			break;
		}
	}

    @Override
    /**
     * 重写返回键操作
     * @param keyCode - 被点击的键码
     * @param event - 键事件
     * @see android.support.v4.app.FragmentActivity#onKeyDown(int, android.view.KeyEvent)
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //若当前fragments.size() > 1，则移除当前fragment并显示上一次选中的fragment
            if (goBack()) {
                return true;
            }
            //若当前fragments.size() = 1，则若exit为true，就推出应用程序，否则弹出提示信息
            if (exit) {
                Application.release(this);
                finish();
            } else {
                makeToast(R.string.login_exit);
                exit = true;
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 自定义提示信息
     * @param resId - 提示字符串id
     * @see com.androidplus.ui.ToastManager#makeToast(java.lang.String, boolean, boolean)
     */
    private void makeToast(int resId) {
        ToastManager.getInstance(this).makeToast(getString(resId), false, false);
    }

    @Override
    /**
     * 当网络请求成功时调用该方法
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public <T> void onSuccess(DownloadParams.PARSING_TYPE type, T response, Object obj){
		super.onSuccess(type, response, obj);

		switch (type) {
		case LOGIN_URL:
			user = (User) response;
            user.setPassword(EncrypAES.getInstance().DecryptorToString(user.getPassword()));
            mUserManager.setCurrentUser(user);
			startActivity(MainTabActivity.getStartIntent(this));
			break;
		case USER_INFO_URL:
			user = (User) response;
			user.setPassword((String) obj);
			mUserManager.login(user);
			setResult(RESULT_OK);
			finish();
			break;
		default:
			break;

		}

	}
}
